﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mmoss.web;
using mmoss.orm;

public partial class Private_POS_Inventory : PageBase 
{
    protected override void Page_Load(object sender, EventArgs e)
    {
        btnAdd.Click += new EventHandler(btnAdd_Click);
        ddlVendor.SelectedIndexChanged += new EventHandler(ddlVendor_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
        buildpulldowns();
        ddlVendor.AutoPostBack = true;
        base.Page_Load(sender, e);
            }
    }

    void btnAdd_Click(object sender, EventArgs e)
    {
        //todo - add in MMC stuff
        //add item to inventory
        Inventory l_inventory = new Inventory();
        l_inventory.mmcID = 1;
        l_inventory.inventoryItemID = int.Parse(ddlItem.SelectedItem.Value);
        l_inventory.insertDate = DateTime.Today;
        l_inventory.Quant = 0;
        l_inventory.userID=LoginUser.userID;

        dbconn.LinqContext.Inventories.InsertOnSubmit(l_inventory);
        dbconn.LinqContext.SubmitChanges();

    }

    void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
    {
        //changed vendor value
        int i_vendorSelected=int.Parse(((DropDownList)sender).SelectedItem.Value);
        buildProductsPull(i_vendorSelected);
    }
    private void buildProductsPull(int l_iVendorID)
    {
        ddlItem.DataSource = dbconn.LinqContext.InventoryItems.Where(p => p.vendorID == l_iVendorID).ToList();
        ddlItem.DataValueField = "Value";
        ddlItem.DataTextField = "Text";
        ddlItem.DataBind();

    }
    private void buildpulldowns()
    {
        ddlVendor.DataSource = dbconn.LinqContext.Vendors;
        ddlVendor.DataValueField = "Value";
        ddlVendor.DataTextField = "Text";
        ddlVendor.DataBind();
        ListItem l_item = new ListItem();
        //ddlVendor.Items.Add(
        buildProductsPull(int.Parse(ddlVendor.SelectedItem.Value));

        //build current inventory
        //tvInventory.DataSource = dbconn.LinqContext.InventoryItemTypes.ToList();
        foreach(InventoryItemType l_type in dbconn.LinqContext.InventoryItemTypes.Where(p=>p.InventoryItems.Where(j=>j.Inventories.Count()>0).Count()>0).ToList())
        {
            TreeNode l_newNode = new TreeNode(l_type.InventoryTypeDesc + l_type.InventoryItems,l_type.InventoryTypeID.ToString());
            tvInventory.Nodes.Add(l_newNode);
            PopulateSubLevel(l_type.InventoryTypeID, l_newNode);
        }
    }
    private void PopulateSubLevel(short parentid,TreeNode parentNode)
    {
        foreach(InventoryItem l_item in dbconn.LinqContext.InventoryItems.Where(p=>p.itemTypeID==parentid).ToList())
        {
            parentNode.ChildNodes.Add(new TreeNode(l_item.itemShortDesc, l_item.Id.ToString()));
        }
    }
}